package chatTest;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;

public class Send implements Runnable {

	private BufferedReader console;
	private DataOutputStream dos;
	private Boolean IsRunning = true;

	/**
	 * 初始化
	 */
	public Send() {
		console = new BufferedReader(new InputStreamReader(System.in));
	}

	public Send(Socket client) {
		this();
		try {
			dos = new DataOutputStream(client.getOutputStream());
		} catch (IOException e) {
			e.printStackTrace();
			IsRunning = false;
			Close.closeAll(dos, console);
		}
	}

	/**
	 * 获取数据
	 * 
	 * @return
	 */
	private String getMsgFromConsole() {
		try {
			return console.readLine();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return "";
	}

	/**
	 * 发送数据
	 */
	public void send() {
		String msg = getMsgFromConsole();
		if (null != msg && !"".equals(msg)) {
			try {
				dos.writeUTF(msg);
				dos.flush();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				Close.closeAll(dos, console);
			}
		}
	}

	/**
	 * 运行线程
	 */
	@Override
	public void run() {
		for (; IsRunning;) {
			send();
		}
	}
}